<?php

namespace app\common\model;

use app\common\model\ServicePackage;

class ServiceBind extends BaseModel
{
    protected $name = "service_bind";

    /**
     * 获取数据列表
     */
    public function getList()
	{
		return $this->order('created_at', 'desc')->paginate($this->pageLimit);
	}

    /**
     * 添加数据
     * @param array $data
     * @return string
     */
    public function addData(array $param): string
    {
        //服务项
        $data['item_id'] = $param['item_id'];
        $data['name'] = $param['name'];
        $data['item_code'] = $param['unique_no'];
        $data['deleted_at'] = $param['deleted_at'];
        $data['creator_id'] = $param['creator_id'];
        $data['parent_id'] = 0;
        $data['children'] = [];
        
        //服务包
        foreach($param['children'] as $key => $val)
        {
            $item['id'] = $val['id'];
            $item['parent_id'] = $param['item_id'];
            $item['name'] = $val['name'];
            $item['item_code'] = $val['unique_no'];

            //服务内容
            $content = (new ServicePackage)->where('id', $val['id'])->field('contentList')->find()->toArray();
            foreach ($content['contentList'] as $k => $v)
            {
                $content['contentList'][$k]['parent_id'] = $val['id'];
            }
 
            $item['children'] = $content['contentList'];
            $data['children'][] = $item;
        }
        return $this->save($data);
    }

    /**
     * 更新数据
     * @param array $data
     * @return bool
     */
    public function saveData($id, array $data): bool
    {
        $model = self::find($id);
        return $model->save($data);
    }

    /**
     * 获取单条数据
     * @return array
     */
    public function getOne($id): array
    {
        return $this->where('id', $id)->select()->toArray();
    }

    /**
     * 获取绑定的服务包
     * @param string $item_id
     * @return array
     */
    public function getFwPack(string $item_id): array
    {
        $bind = $this->where('item_id', $item_id)->field('name,children')->find();

        if (isset($bind['children']) && !empty($bind['children']))
        {
            $children = $bind->toArray();

            $pack = [];
            foreach ($children['children'] as $key => $val)
            {
                $pack[] = $val['id'];
            }
            $data['title']['name'] = $children['name'].'('.count($children['children']).'项)';
            $data['pack'] = (new ServicePackage)->getWhereIds($pack);
            return $data;
        }else{
            return [];
        }
    }
}